/**
 * \file
 *
 * \brief Empty user application template
 *
 */

/*
 * Include header files for all drivers that have been imported from
 * Atmel Software Framework (ASF).
 */
#include <asf.h>

/* CPU load timer */
#define CPU_TIMER TCC0

#define TC_PERIOD_MS 1000

static void cpu_timer_init(void);
static void tick_handler(void);
static void cpu_timer_start(void);
static void cpu_timer_stop(void);


int main (void)
{
	board_init();
	pmic_init();
	sysclk_init();
	cpu_timer_init();
	
	cpu_irq_enable();
	
	ioport_set_pin_low(LED0);
	
	while (1)
	{
	}

	// Insert application code here, after the board has been initialized.
}


/* Timer initialization */
static void cpu_timer_init(void)
{
	uint16_t period = sysclk_get_per_hz() / 64 / 1000 * TC_PERIOD_MS -1;
	
	tc_enable(&CPU_TIMER);
	tc_set_wgm(&CPU_TIMER, TC_WG_NORMAL);
	tc_set_overflow_interrupt_callback(&CPU_TIMER, tick_handler);
	tc_set_overflow_interrupt_level(&CPU_TIMER, TC_INT_LVL_LO);
	tc_write_period(&CPU_TIMER, period);	
	tc_write_count(&CPU_TIMER, 0);	
	tc_write_clock_source(&CPU_TIMER, TC_CLKSEL_DIV64_gc);
}

static void tick_handler(void)
{
	uint8_t my_var;
	
	my_var = ~PORTE.OUT;
	my_var = my_var << 1;
	if (my_var == 0x00)
			my_var = 1;
	PORTE.OUT = ~my_var;
			
	if (!ioport_get_pin_level(GPIO_PUSH_BUTTON_0))
	{
		CPU_TIMER.PER = CPU_TIMER.PER >> 1 ;
		if (CPU_TIMER.PER == 0)
			CPU_TIMER.PER = 0xFFFF;
	}
}	


/* This function starts the TC */
static  void cpu_timer_start(void)
{
	tc_write_count(&CPU_TIMER, 0);
	tc_write_clock_source(&CPU_TIMER, TC_CLKSEL_DIV64_gc);
}

/* This function stops the TC */
static  void cpu_timer_stop(void)
{
	tc_write_clock_source(&CPU_TIMER, TC_CLKSEL_OFF_gc);
}